231C - To Add or Not to Add - CodeForces Solution


binary search sortings two pointers *1600

Please click on ads to support us..

Python Code:



from cmath import inf


n,k = list(map(int, input().split(' '))) 
nums = list(map(int, input().split(' ')))


nums.sort(reverse=True)
first = nums[0]
        
li = []
count = 0
i = 0
j = 0
ans_val = []

while j < len(nums):

    diff = nums[i] - nums[j]

    if diff <= k:
        k-=diff
        j+=1

    elif diff > k:
        
        count = j-i
        val = nums[i]
        i+=1
        k += ((j-i)*(nums[i-1] - nums[i]))
        if len(li)==0:
            li.append(count)
            ans_val.append(val)
        else:
            if count>=li[-1]:
                li.append(count) 
                ans_val.append(val)

count = j-i
val = nums[i]
i+=1
if len(li)==0:
    li.append(count)
    ans_val.append(val)
else:
    if count>=li[-1]:
        li.append(count) 
        ans_val.append(val)

if li==[]:
    li.append(j-i)
    ans_val.append(nums[i])
elif (j-i)>li[-1]:
    li.append(j-i)
    ans_val.append(nums[i])

print(li[-1], ans_val[-1]) 

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

bool good (vector<ll> &sums, ll num, ll k, ll l, ll r) {
    return k >= num - (sums[r] - sums[l]); 
}

ll solve (vector<ll> &sums, ll num, ll k, ll j) {
    ll l = -1, r = j;

    while (l + 1 < r) {
        ll m = (l + r) / 2; 
        ll len = j - m + 1;
        if (good(sums, num * (len - 1), k, j - len, j - 1)) r = m;
        else l = m;  
    }

    return j - r + 1;
}

int main () {
    ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);

    ll n, k; cin >> n >> k;

    vector<ll> nums(n + 1, -1e12), sums(n + 1);

    for (int i = 1; i <= n; i++) {
        cin >> nums[i];
        
    }

    sort(nums.begin(), nums.end());

    for (int i = 1; i <= n; i++) {
        sums[i] = nums[i] + sums[i - 1];
    }


    ll cnt = 0, num = 0;

    for (ll i = 1; i <= n; i++) {
        ll now = solve(sums, nums[i], k, i);
        if (now > cnt) {
            cnt = now, num = nums[i];
        }
    }

    cout << cnt << " " << num;

    return 0;
}


Comments

Submit
0 Comments
More Questions

1541A - Pretty Permutations
1632C - Strange Test
673A - Bear and Game
276A - Lunch Rush
1205A - Almost Equal
1020B - Badge
1353A - Most Unstable Array
770A - New Password
1646B - Quality vs Quantity
80A - Panoramix's Prediction
1354B - Ternary String
122B - Lucky Substring
266B - Queue at the School
1490A - Dense Array
1650B - DIV + MOD
1549B - Gregor and the Pawn Game
553A - Kyoya and Colored Balls
1364A - XXXXX
1499B - Binary Removals
1569C - Jury Meeting
108A - Palindromic Times
46A - Ball Game
114A - Cifera
776A - A Serial Killer
25B - Phone numbers
1633C - Kill the Monster
1611A - Make Even
1030B - Vasya and Cornfield
1631A - Min Max Swap
1296B - Food Buying